package cn.xuexiluxian.open.common.response;

import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.exception.BusinessException;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.beans.Transient;
import java.io.Serializable;

/**
 * 返回数据
 */
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor
public class ResponseResult<T> implements Serializable {

    /**
     * 状态码
     */
    private String code;
    /**
     * 状态信息
     */
    private String msg;
    /**
     * 结果数据
     */
    private T data;

    /**
     * 返回成功状态
     */
    public static ResponseResult ok() {
        return new ResponseResult(ResultStatusCodeEnum.HTTP_SUCCESS.getCode(), ResultStatusCodeEnum.HTTP_SUCCESS.getDesc(), null);
    }

    /**
     * 返回成功数据
     *
     * @param data 数据
     */
    public static <T> ResponseResult<T> ok(T data) {
        return new ResponseResult(ResultStatusCodeEnum.HTTP_SUCCESS.getCode(), ResultStatusCodeEnum.HTTP_SUCCESS.getDesc(), data);
    }

    /**
     * 返回错误结果
     *
     * @param ResultStatusCodeEnum 状态码
     */
    public static <T> ResponseResult<T> error(ResultStatusCodeEnum ResultStatusCodeEnum) {
        return new ResponseResult(ResultStatusCodeEnum.getCode(), ResultStatusCodeEnum.getDesc(), null);
    }

    /**
     * 返回错误结果
     *
     * @param msg 错误信息
     */
    public static <T> ResponseResult<T> error(String msg) {
        return new ResponseResult(ResultStatusCodeEnum.HTTP_ERROR.getCode(), msg, null);
    }

    /**
     * 返回错误结果: 带错误数据
     *
     * @param ResultStatusCodeEnum 状态码
     * @param data                 错误数据
     */
    public static <T> ResponseResult<T> error(ResultStatusCodeEnum ResultStatusCodeEnum, T data) {
        return new ResponseResult(ResultStatusCodeEnum.getCode(), "", data);
    }

    public static <T> ResponseResult<T> error(BusinessException e) {
        return new ResponseResult(e.getCode(), e.getMessage(), null);
    }

    public static <T> ResponseResult<T> error(String code, String msg) {
        return new ResponseResult(code, msg, null);
    }

    @Transient
    public boolean isOk() {
        return ResultStatusCodeEnum.HTTP_SUCCESS.getCode().equals(code);
    }

}
